import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { DeviceList, DeviceStatus } from '@/types/index'
import { getDeviceInfoApi, getDeviceStatusApi } from '@/services/index'
import { useMemberStore } from '@/stores'
import type { HarDwareDetai } from '@/types/equipment'
import { getHarDwareDetailApi } from '@/services/equipment'
import {getAlarmListApi} from '@/services/alarm'
export const useDeviceStore = defineStore('device', () => {
  const deviceList = ref<DeviceList>()
  const devicedetail = ref<DeviceStatus>()
  const HarDwareDetail = ref<HarDwareDetai>()
  const sex = ref<string>()
  const HarDwaresex = ref<string>()
  const memberStore = useMemberStore()
  //请求用户名下设备列表和一次实时数据
  const getDeviceList = async () => {
    const {
      data: { devices },
    } = await getDeviceInfoApi(memberStore.profile!.id)
    deviceList.value = devices
    //devices.forEach(async (item)=>{}) 是异步函数,每一次回调会await，但是整个foreach不会await，所以会导致数据不同步
    deviceList.value.forEach(async (item) => {
      const { data } = await getDeviceStatusApi(item.id)
      console.log(data.isInBed, '当前设备实时数据')
      item.isInBed = data.isInBed
      item.breath = data.breath
      item.heart = data.heart
    })
    //console.log(devices, '2222')

    //console.log(deviceList.value ,'当前用户设备列表')
  }
  const clearDeviceList = () => {
    deviceList.value = undefined
  }
  //设置当前设备的实时数据
  const getDeviceData = async (id: number = deviceList.value![0].id) => {
    const { data } = await getDeviceStatusApi(id)
    devicedetail.value = data
    switch (data.sex) {
      case 0:
        sex.value = '保密'
        break
      case 1:
        sex.value = '男'
        break
      case 2:
        sex.value = '女'
        break
    }
  }
  const clearDeviceData = () => {
    devicedetail.value = undefined
  }
  //设置硬件信息
  const getHarDwareDetail = async (deviceNum: string) => {
    const { data } = await getHarDwareDetailApi(deviceNum)
    HarDwareDetail.value = data
    switch (data.sex) {
      case 0:
        HarDwaresex.value = '保密'
        break
      case 1:
        HarDwaresex.value = '男'
        break
      case 2:
        HarDwaresex.value = '女'
        break
    }
    console.log(HarDwareDetail.value+'当前设备硬件信息')
  }
  const clearHarDwareDetail = () => {
    HarDwareDetail.value = undefined
  }
  

  return {
    deviceList,
    devicedetail,
    sex,
    HarDwareDetail,
    HarDwaresex,
    getDeviceList,
    clearDeviceList,
    getDeviceData,
    clearDeviceData,
    getHarDwareDetail,
    clearHarDwareDetail,
  }
  
})
